import os
import time

is_debugging = False
notice_when_check_dir = False
keep_latest: bool = True
SUCCESS_DICT = {True: 'successfully', False: 'failed'}


class file_sync:

    local_path: str
    remote_path: str

    def __init__(self, remote: str, local: str):
        self.remote_path = os.path.abspath(remote)
        self.local_path = os.path.abspath(local)
        # self.sync()

    @staticmethod
    def get_my_mtime(path:str):
        return int(time.strftime('%Y%m%d%H%M%S', time.gmtime(os.path.getmtime(path))))

    # 下载指定目录下的指定文件，留空意味确保此前ftp和os的当前目录如预期
    def pull_file(self, file: str):
        remote_file=os.path.join(self.remote_path,file)
        local_file=os.path.join(self.local_path,file)

        if keep_latest:
            if os.path.isfile(local_file):
                if file_sync.get_my_mtime(remote_file) <= file_sync.get_my_mtime(local_file):
                    if is_debugging:
                        print(f'no pull {remote_file}.')
                    return
        with open(local_file, 'wb') as loc:
            with open(remote_file, 'rb') as rem:
                print(f'pulling {remote_file} -> {local_file} ......')
                loc.write(rem.read())
                loc.flush()

    # 下载整个目录下的文件，请确保此前ftp和os的当前目录如预期
    def pull_filetree(self, treeroot_dir: str):
        # rem
        if is_debugging:
            print("remote dir:", os.path.abspath(treeroot_dir))

        os.chdir(self.local_path)
        # loc
        if not os.path.exists(os.path.join(self.local_path,treeroot_dir)):
            os.makedirs(treeroot_dir)
        
        self.remote_path=os.path.join(self.remote_path,treeroot_dir)
        self.local_path=os.path.join(self.local_path,treeroot_dir)

        #rem
        os.chdir(self.remote_path)
        remote_names = os.listdir()
        if is_debugging:
            print("remote names:", remote_names)
        for file in remote_names:
            if os.path.isdir(os.path.join(self.remote_path,file)):
                if is_debugging or notice_when_check_dir:
                    print(f'Checking directory: {file} ......')
                self.pull_filetree(file)
            else:
                self.pull_file(file)
        self.remote_path=os.path.split(self.remote_path)[0]
        self.local_path=os.path.split(self.local_path)[0]
        os.chdir("..")
        return True

    def sync(self, dir: str):
        print('-----------------------')
        print('start pulling......')
        print(f'pulled {SUCCESS_DICT[self.pull_filetree(dir)]}.')
        print('-----------------------')
        # self.local_path, self.remote_path = self.remote_path, self.local_path
        # print('start pushing......')
        # print(f'upload {SUCCESS_DICT[self.pull_filetree(dir)]}.')
        # print('-----------------------')


if __name__ == '__main__':
    # fs=file_sync(remote=r'D:',local=r'Z:\0资料')
    # for d in ['爱好','理工']:
    #     fs.pull_filetree(d)
    
    fs=file_sync(remote=r'D:',local=r'F:')
    for d in ['个人文件','MailMasterData','资料','历史文件']:
        fs.pull_filetree(d)